from pydantic import BaseModel
from sqlalchemy import Table, Column, between


def generate_query_conditions(params: BaseModel, table: Table):
    """自动生成查询条件"""
    operators = {
        '==': lambda col, val: col == val,
        '!=': lambda col, val: col != val,
        '>': lambda col, val: col > val,
        '>=': lambda col, val: col >= val,
        '<': lambda col, val: col < val,
        '<=': lambda col, val: col <= val,
        'LIKE': lambda col, val: col.like(f'%{val}%'),
        'ILIKE': lambda col, val: col.ilike(f'%{val}%'),  # 转换成小写的like
        'START': lambda col, val: col.startswith(val),
        'IN': lambda col, val: col.in_(val if isinstance(val, list) else [val]),
        'NOT_IN': lambda col, val: ~col.in_(val if isinstance(val, list) else [val]),
        'BETWEEN': lambda col, val: between(col, val[0], val[1]),
    }

    where_clauses = []
    if not hasattr(params, 'Config'):
        return where_clauses
    field_operator_mapping = getattr(params.Config, 'field_operator_mapping', {})

    for field_name, field_value in params.dict(exclude_unset=True).items():
        if field_value is not None:
            column: Column = getattr(table.c, field_name, None)
            if ((isinstance(field_value, str) and field_value == '')
                    or (isinstance(field_value, list) and len(field_value) == 0)
                    or column is None):
                continue  # 跳过空字符串的条件
            if not field_operator_mapping.__contains__(field_name):
                continue  # 不存在条件配置时不生成条件
            operator = field_operator_mapping.get(field_name, '==')
            operation = operators.get(operator)
            if operation:
                if operator == 'IN':
                    if isinstance(field_value, str):
                        field_value = field_value.split(',')
                    if (isinstance(field_value, str) or isinstance(field_value, list)) and len(field_value) == 0:
                        continue
                where_clauses.append(operation(column, field_value))
    return where_clauses
